-module(register_block).
-include_lib("nitrogen/include/wf.inc").
-compile(export_all).

%% The register->menu block does not go on it's own, it is included with the login->menu block.

						%Builders
assemble_header(X) ->
    X.

assemble_menu(X) ->
    X ++ [#link{text = "S'inscrire", actions=helper:act(?MODULE, {register, menu})}].

assemble_body(X) ->
    X ++ [ #p{},
	   #label{ text="Nom d'utilisateur : " },
	   #textbox{ id=rb_nick },

	   #p{},
	   #label{ text="Mot de passe : " },
	   #password{ id=rb_pass },

	   #p{},
	   #label{ text="Confirmez : " },
	   #password{ id=rb_confirm },

	   #p{},
	   #label{ text="Email : " },
	   #textbox{ id=rb_email },

	   #p{},
	   #button{ id=rb_register, text="S'inscrire !", actions=helper:act(?MODULE, {register, body}) } ].
						%Wiring

wire() ->   
    wf:wire(rb_register, rb_nick, #validate {
			validators=[
				    #is_required { text = "X" }
				   ] }),
    wf:wire(rb_register, rb_pass, #validate {
			validators=[
				    #is_required { text="X" },
				    #min_length { length=5, text=">5" }
				   ] }),
    wf:wire(rb_register, rb_confirm, #validate {
			validators=[
				    #is_required { text="X" },
				    #confirm_password { password=rb_pass,  text="X" }
				   ] }),
    wf:wire(rb_register, rb_email, #validate { 
			validators=[
				    #is_required { text="X" },
				    #is_email { text="X" }
				   ]}),
    ok.
						%Behavior
behave(_) ->
    wf:redirect("/web/index"),
    ok.
						%Events
event({register, menu}) ->
    wf:update(lb_rpanel, #rounded_panel {color=gray, body = assemble_body( [] ) ++ [#br{}, #link{text="Retour", actions=helper:act(login_block, {refresh_panel, menu})}] }),
    wire(),
    ok;

event({register, body}) ->
    [Nick] = wf:q(rb_nick),
    [Pass] = wf:q(rb_pass),
    [Email] = wf:q(rb_email),
    case db:add(member, {Nick, Pass, Email}) of
	{ok, _} -> behave({register, body});
	{error, bad_nick} -> wf:flash("Votre nom d'utilisateur est déjà utilisé, veuillez en choisir un nouveau");
	{error, Reason} -> wf:flash("Erreur : " ++ Reason);
	_ -> wf:flash("Erreur inconnue")
    end;

event(_) ->
    ok.
